package com.WGrape.wgrapecodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;

import java.util.List;

/**
 * @author with葡萄成熟时
 * @version 1.0
 */

public class demo {

    public static void main(String[] args) throws InterruptedException {
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();


        // 5. 列出所有镜像
        System.out.println("\n=== 列出所有镜像 ===");
        List<Image> images = dockerClient.listImagesCmd().exec();
        images.forEach(image -> System.out.println(
                "ID: " + image.getId() +
                        ", Tags: " + String.join(",", image.getRepoTags())));



        // 4. 定义要拉取的镜像
        String imageName = "openjdk:8-alpine";

        System.out.println("\n=== 开始拉取镜像 " + imageName + " ===");

        // 5. 拉取镜像并显示进度
        dockerClient.pullImageCmd(imageName)
                .exec(new PullImageResultCallback() {
                    @Override
                    public void onNext(PullResponseItem item) {
                        // 显示拉取进度
                        if (item.getProgressDetail() != null && item.getProgressDetail().getCurrent() != null) {
                            System.out.printf("进度: %s %d/%d%n",
                                    item.getId(),
                                    item.getProgressDetail().getCurrent(),
                                    item.getProgressDetail().getTotal());
                        } else if (item.getStatus() != null) {
                            System.out.println(item.getStatus());
                        }
                        super.onNext(item);
                    }
                })
                .awaitCompletion();

        System.out.println("\n镜像 " + imageName + " 拉取完成!");
    }
}
